// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 全局通用JS函数 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

//给字符串增加startsWith方法
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (search, pos) {
        return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
    };
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (str) {
        if (str == null || str == "" || this.length == 0 || str.length > this.length)
            return false;
        if (this.substring(this.length - str.length) == str) {
            return true;
        } else {
            return false;
        }
        return true;
    };
}

//检测浏览器版本
var browser = {};
browser.ua = navigator.userAgent;
browser.ie = browser.ua.indexOf('Trident') > -1; //IE
browser.opera = browser.ua.indexOf('Presto') > -1; //opera
browser.webkit = browser.ua.indexOf('AppleWebKit') > -1; //webkit
browser.firefox = browser.ua.indexOf('Gecko') > -1 && browser.ua.indexOf('KHTML') == -1; //firefox
browser.mobile = browser.ua.indexOf("Mobile") > -1 || !!browser.ua.match(/AppleWebKit.*Mobile.*/); //是否为移动终端
browser.ios = !!browser.ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
browser.android = browser.ua.indexOf('Android') > -1 || browser.ua.indexOf('Linux') > -1; //android
browser.iphone = browser.ua.indexOf('iPhone') > -1; //iphone
browser.ipad = browser.ua.indexOf('iPad') > -1; //ipad
browser.dingMobile = browser.ua.indexOf('AliApp(DingTalk') > -1;
browser.dingPc = browser.ua.indexOf('AliApp(DingTalk') === -1 && browser.ua.indexOf('DingTalk') > -1;

//全局对象定义
var g = {};

//载入layer
if (browser.mobile && typeof layer != "undefined") {
    //移动
    layer.alert = function (msg, option, callback) {
        if (typeof option == 'function') {
            callback = option;
            option = {};
        }
        return layer.open({
            content: msg,
            title: option && option.title,
            btn: '确定',
            yes: function (index) {
                layer.close(index);
                (typeof callback == 'function') && callback();
            }
        });
    };
    layer.msg = function (msg, option) {
        return layer.open({
            content: msg,
            skin: 'msg',
            time: (option && option.time) || 5
        });
    };
    layer.confirm = function (msg, option, callback) {
        return layer.open({
            content: msg,
            btn: (option && option.btn) || ['是', '否'],
            yes: function (index) {
                (typeof callback == 'function') && callback(index);
            }
        });
    };
    layer.load = function () {
        return layer.open({type: 2});
    }
} else {
    //PC
    layui.use('layer', function () {
        window.layer = layui.layer;
    });
}

/**
 * 全局加载框
 */
g.loading = function () {
    var selector = false, show = true;
    if (arguments.length == 0) {
        // 没有参数时，表示显示全局的loading层
        selector = false;
        show = true;
    } else if (arguments.length == 1) {
        // 一个参数时
        if (typeof arguments[0] == 'boolean') {
            // 如果参数是boolean，表示控制全局loading的显示和隐藏
            selector = false;
            show = arguments[0];
        } else {
            // 非boolean，表示控制某个页面元素上面的loading
            selector = arguments[0];
            show = true
        }
    } else {
        // 两个参数，表示控制某个元素上面的loading
        selector = arguments[0];
        show = arguments[1];
    }

    if (!selector) {
        if (show === false) {
            layer.close(window.layer_loading_index);
            window.layer_loading_index = 0;
        } else {
            if (window.layer_loading_index) {
                layer.close(window.layer_loading_index);
            }
            window.layer_loading_index = layer.load(0, {
                shade: 0.3
            });
        }
    } else {
        var $selector = typeof selector == 'string' ? $(selector) : selector;
        var $mask = $(selector).next(".element-loading-mask");
        if (show === false) {
            var timeoutIdx = $selector.data("loading-timeout-idx");
            if (timeoutIdx) {
                clearTimeout(timeoutIdx);
            }
            $mask.remove();
        } else {
            if ($mask.length == 0) {
                var height = $selector.outerHeight();
                var width = $selector.outerWidth();
                if (width == 0) {
                    // 宽度为0，说明此时元素所在的父元素不可见或者页面还没渲染完毕，等待一段时间
                    var timeoutIdx = setTimeout(function () {
                        g.loading($selector);
                    }, 500);
                    $selector.data("loading-timeout-idx", timeoutIdx);
                    return;
                }
                var style = "z-index: 99999999; background-color: rgba(0, 0, 0, 0.3); position: absolute;text-align:center;";
                style += "width: " + width + "px;";
                style += "height: " + height + "px;";
                style += "margin-top: -" + height + "px;";
                var imgHeight = height < 60 ? height : 60;
                var imgStyle = "height: " + imgHeight + "px;";
                imgStyle += "margin-top: " + ((height - imgHeight) / 2) + "px";
                var htm = '<div class="element-loading-mask" style="' + style + '">';
                htm += "<img src='../../static/images/loading.svg' style='" + imgStyle + "'/>";
                htm += '</div>';
                $selector.after(htm);
            }
            $mask.show();
        }
    }
};

/**
 * 使得元素在整个页面中居中
 *
 * @param $elem
 * @param minMarginTop
 * @param deltaHeight
 */
g.setElementVerticalMiddle = function ($elem, minMarginTop, deltaHeight) {
    $elem = typeof $elem == 'string' ? $($elem) : $elem;
    var elemHeight = $elem.height();
    var windowHeight = $(window).height();
    if (!minMarginTop) {
        minMarginTop = 0;
    }
    if (!deltaHeight) {
        deltaHeight = 0;
    }
    elemHeight += deltaHeight;
    var marginTop = (windowHeight - elemHeight) / 2;
    if (marginTop < minMarginTop) {
        marginTop = minMarginTop;
    }

    $elem.css("margin-top", marginTop + "px");
};

////////////////////////////////////////////////////////////////
/**
 * 调用api
 *
 * @param mid
 * @param apiName
 * @param args
 * @param callback
 * @returns {*}
 */
function callApi(mid, apiName, args, callback) {
    if (!args) {
        // POST传的参数不能为空数组
        args = {"____t": new Date().getTime()};
    }
    var __callback = function (ret) {
        if (typeof ret != 'object') {
            layer.alert("API调用错误：" + ret, {zIndex: 99999999});
        }
        if (ret.code == 0) {
            layer.alert("API调用错误：" + ret.msg, {zIndex: 99999999});
        }
        if (ret.data && ret.data.lastStatus && ret.data.lastStatus.errcode != 0) {
            layer.alert("API调用错误：" + ret.data.lastStatus.errmsg, {zIndex: 99999999});
        }
        if (typeof callback == 'function') {
            var response = ret.data.response;
            var lastStatus = ret.data.lastStatus;
            callback(response, lastStatus);
        }
    };

    var url = "/core/enterprise.api/" + apiName + "?mid=" + mid;

    $.ajax({
        type: "post",
        url: url,
        data: args,
        async: true,
        success: function (ret) {
            __callback(ret);
        },
        error: function () {
            var ret = {};
            ret.data = {};
            ret.data.response = false;
            ret.data.lastStatus = {};
            __callback(ret);
        }
    });
}

////////////////////////////////////////////////////////////////////////////
//百度统计
var _hmt = _hmt || [];
(function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?9564b9ef6e4bd258c355b757b4eb77e5";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();
